package com.logictech.lims.web.api;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.jeecgframework.p3.core.logger.Logger;
import org.jeecgframework.p3.core.logger.LoggerFactory;
import org.jeecgframework.p3.core.util.MD5Util;
import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.logictech.activity.system.entity.SystemUser;
import com.logictech.activity.system.service.SystemUserService;
import com.logictech.activity.system.vo.LoginUser;
import com.logictech.common.util.SystemEnum;
import com.logictech.common.util.data.StringUtils;
import com.logictech.lims.dto.LoginReq;
import com.logictech.lims.service.LogService;
import com.logictech.wechat.model.responseDto.JsonResp;

@Controller
@RequestMapping({ "/lims/api/login" })
public class ApiLoginController extends BaseController {
	public static final Logger LOG = LoggerFactory.getLogger(ApiLoginController.class);

	@Autowired
	private SystemUserService systemUserService;
	
	@Resource
	private LogService logService;

	@RequestMapping(value = { "/checkUser" }, method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public JsonResp<SystemUser> login(HttpServletRequest request,@RequestBody LoginReq loginReq) throws Exception {
		JsonResp<SystemUser> resp = new JsonResp<SystemUser>();
		String userid = loginReq.getUserId();
		String password = loginReq.getPassword();
		
		if(StringUtils.isEmpty(userid)){
			return new JsonResp<SystemUser>(SystemEnum.ARGUMENT_EMPTY.getErrCode(), "用户编码" + SystemEnum.ARGUMENT_EMPTY.getErrChineseMsg());
		}
		
		if(StringUtils.isEmpty(password)){
			return new JsonResp<SystemUser>(SystemEnum.ARGUMENT_EMPTY.getErrCode(), "用户密码" + SystemEnum.ARGUMENT_EMPTY.getErrChineseMsg());
		}
		
		try {
			LoginUser user = this.systemUserService.queryUserByUserId(userid);
			
			if (user != null) {
				String passwordEncode = MD5Util.MD5Encode(password, "utf-8");
				// 判断是否允许登录app
				if(!"1".equals(user.getLoginApp())){
					return new JsonResp<SystemUser>(SystemEnum.UNAUTHORIZED_AC_ERR.getErrCode(), SystemEnum.UNAUTHORIZED_AC_ERR.getErrChineseMsg());
				}
				if(("NORMAL".equals(user.getUserStat()))){
					if ((passwordEncode != null) && (passwordEncode.equals(user.getPassword()))
							) {
						SystemUser systemUser = new SystemUser();
						PropertyUtils.copyProperties(systemUser, user);
						systemUser.setToken(createToken(user.getUserId()));
						systemUserService.doEdit(systemUser);
						resp.setInfo(systemUser);
						
						logService.doAdd(user.getUserName() + "登录系统（移动端）");
						request.getSession().setAttribute("platform", "1");
				        return resp;
					}else{
						return new JsonResp<SystemUser>(SystemEnum.LOGIN_PASSWORD_ERROR.getErrCode(), SystemEnum.LOGIN_PASSWORD_ERROR.getErrChineseMsg());
					}
				}else{
					return new JsonResp<SystemUser>(SystemEnum.LOGIN_FORBIDDEN.getErrCode(), "用户【" + userid + "】无效");
				}
			} else {
				LOG.info("登录失败：用户【" + userid + "】不存在");
				return new JsonResp<SystemUser>(SystemEnum.LOGIN_USER_ERROR.getErrCode(), SystemEnum.LOGIN_USER_ERROR.getErrChineseMsg());
			}
		} catch (Exception e) {
			LOG.info("登录失败：用户【" + userid + "】" + e.getMessage());
			return new JsonResp<SystemUser>(SystemEnum.SYS_ERROR.getErrCode(), SystemEnum.SYS_ERROR.getErrChineseMsg());
		}
	}
	
	@RequestMapping(value = { "/logout" }, method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		LoginUser user = (LoginUser) request.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
		if(user != null){
			logService.doAdd(user.getUserName() + "退出系统（移动端）");
		}
		request.getSession().removeAttribute("OPERATE_WEB_LOGIN_USER");
		request.getSession().removeAttribute("platform");
	}
	
	/**
     * Token 建立
     *
     * @param userId
     * @return
     */
    public String createToken(String userId) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer(128);
        String valueBeforeMD5 = "";
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            // Should not happen
            throw new IllegalStateException(e);
        }

        long time = System.currentTimeMillis();
        String fourRand = StringUtils.getRandomNum(4);

        sbValueBeforeMD5.append(userId);
        sbValueBeforeMD5.append(Long.toString(time));
        sbValueBeforeMD5.append(fourRand);

        valueBeforeMD5 = sbValueBeforeMD5.toString();
        md5.update(valueBeforeMD5.getBytes());

        byte[] array = md5.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int j = 0; j < array.length; ++j) {
            int b = array[j] & TWO_BYTES;
            if (b < PAD_BELOW) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(b));
        }

        return sb.toString();
    }
    
    /**
	 * 获取位置列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/getUserNameList" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<List<SystemUser>> getUserNameList(){
		
		List<SystemUser> userList = systemUserService.queryLoginList();
        JsonResp<List<SystemUser>> resp = new JsonResp<List<SystemUser>>();
        resp.setInfo(userList);
        return resp;
    }
    
    /**
     * token 用
     */
    public static final int TWO_BYTES = 0xFF;
    

    /**
     * token 用
     */
    public static final int PAD_BELOW = 0x10;
}
